<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions">
      <template #form="{ form }">
        <VGroup>
          <el-select v-model="form.input.type" style="width: 100px">
            <el-option label="采购单号" value="purchase_no"></el-option>
            <el-option label="开票清单号" value="billing_no"></el-option>
            <el-option label="发票号码" value="invoice_no"></el-option>
            <el-option label="开票合同" value="contract_no"></el-option>
            <el-option label="送货清单" value="deliver_contract_no"></el-option>
            <el-option label="开票清单" value="list_contract_no"></el-option>
            <el-option label="开票明细" value="detail_contract_no"></el-option>
          </el-select>
          <VBatchInput v-model="form.input.value" @search="query" class="w-60" />
        </VGroup>
        <VSelect v-model="form.supplier_name" placeholder="供应商" type="supplierName" allow-create style="min-width: 200px" multiple collapse-tags clearable filterable />
        <VGroup>
          <el-select v-model="form.skuInfo.type" class="w-28">
            <el-option label="sku" value="sku"></el-option>
            <el-option label="赛盒SKU" value="sai_he_sku"></el-option>
            <el-option label="自定义sku" value="custom_sku"></el-option>
          </el-select>
          <el-input v-model="form.skuInfo.value" placeholder="请输入" class="w-40"></el-input>
        </VGroup>
        <VCascader v-model="form.purchase_user_id" placeholder="采购人员" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.period_id" placeholder="结算方式" type="period" multiple collapse-tags style="min-width: 220px" />
        <VCascader v-model="form.department_name" placeholder="部门" type="department" multiple collapse-tags checkStrictly :level="2" style="min-width: 160px" />
        <VSelect v-model="form.billing_status" placeholder="录入状态" :options="options.billing_status" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.invoice_status" placeholder="推送状态" :options="options.invoice_status" multiple collapse-tags style="min-width: 160px" />
        <el-input v-model="form.invoice_name" placeholder="开票品名" class="w-44" />
        <el-input v-model="form.invoice_unit" placeholder="开票单位" class="w-44" />
        <VSelect v-model="form.upload_file" placeholder="文件是否上传" :options="options.upload_file" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.is_billing_contract" placeholder="是否生成开票合同" :options="options.is_contract" style="min-width: 160px" />
        <VSelect v-model="form.is_billing_deliver" placeholder="是否生成送货清单" :options="options.is_contract" style="min-width: 160px" />
        <VSelect v-model="form.is_billing_detail" placeholder="是否生成开票清单" :options="options.is_contract" style="min-width: 160px" />
        <VGroup>
          <el-select v-model="form.dateRange.type" style="width: 100px">
            <el-option label="生成时间" value="create_time"></el-option>
            <el-option label="入库时间" value="inbound_time"></el-option>
          </el-select>
          <VDate v-model="form.dateRange.value" />
        </VGroup>
      </template>
      <template #toolbar_btns>
        <VButton auth="/purchase/finance/verification/billing/contract" type="primary" @click="handleBatch('create')">
          <svg-icon icon-class="rizhi" class="mr-1" style="font-size: 15px" />生成开票合同
        </VButton>
        <VButton auth="/purchase/finance/verification/billing/delivery" type="primary" @click="handleBatch('delivery')">生成送货清单</VButton>
        <VButton auth="/purchase/finance/verification/billing/bill" type="primary" @click="handleBatch('bill')">生成开票清单</VButton>
        <VButton auth="/purchase/finance/verification/billing/bill_detail" type="primary" @click="handleBatch('bill_detail')">生成开票明细</VButton>
        <VButton auth="/purchase/finance/verification/billing/importFile" @click="() => importFileRef.open()">文件导入</VButton>
        <VButton auth="/purchase/finance/verification/billing/cancel" @click="handleBatch('cancel')">作废</VButton>
        <VButton auth="/purchase/finance/verification/billing/print" :loading="loadings.print" @click="handleBatch('print')">批量打印</VButton>
        <VImport auth="/purchase/finance/verification/billing/import" :tableRef="tableRef" importUrl="/v1/finance/billing/import-match-invoice"
                 downloadUrl="https://xc-pms.oss-cn-shenzhen.aliyuncs.com/template/%E5%8F%91%E7%A5%A8%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF%20.xlsx" class="ml-auto" @success="query">发票录入匹配
        </VImport>
        <VImport auth="/purchase/finance/verification/billing/import" :tableRef="tableRef" importUrl="/v1/finance/billing/import-invoice"
                 downloadUrl="https://xc-pms.oss-cn-shenzhen.aliyuncs.com/template/invoice_template.xlsx" @success="query" />
        <VAuth auth="/purchase/finance/verification/billing/export">
          <el-dropdown trigger="click" @command="handleExport">
            <el-button>
              <i class="dk-iconfont icon-Upload" />
              导出<i class="dk-iconfont icon-ArrowDown" />
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="billing">单据维度导出</el-dropdown-item>
                <el-dropdown-item command="billing-detail">明细维度导出</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <VExport ref="exportRef" class="absolute -right-full" :name="exportName" mainKey="b_id" task :tableRef="tableRef" />
        </VAuth>
      </template>
    </VTable>
    <Enter ref="enterRef" :api="api" @success="query" />
    <Contract ref="contractRef" :options="options" @success="query" />
    <ImportFile ref="importFileRef" :options="options" @success="query" />
    <VLog ref="logRef" />
    <ViewImage ref="viewImageRef" />
    <BatchPrint ref="batchPrintRef" />
  </VPage>
</template>

<script setup lang="jsx" name="Account">
  import api from './api'
  import VImport from '@/components/VImport'
  import Enter from './components/Enter'
  import Contract from './components/Contract'
  import ImportFile from './components/ImportFile'
  import { getOption } from '@/api/public'
  import { resMessage } from '@/utils/res'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { yesno } from "@/utils"
  import BatchPrint from './components/BatchPrint'
  const router = useRouter();
  const baseName = 'billing'
  const tableRef = ref()
  const logRef = ref()
  const viewImageRef = ref()
  const loadings = reactive({})
  // 查询
  const query = () => {
    tableRef?.value.query()
  }

  const exportRef = ref()
  const exportName = ref('')
  const handleExport = (val) => {
    exportName.value = val
    nextTick(() => {
      exportRef?.value.open()
    })
  }

  // 获取options
  const options = ref({})
  Promise.all([
    getOption({ type: baseName }).then(res => res.data),
    getOption({ type: 'payment' }).then(res => res.data),
    Promise.resolve({ test: [{ label: '没有数据', value: 1 }] })
  ]).then(res => {
    options.value = res.reduce((acc, cur) => (((acc = { ...acc, ...cur }), acc)), {})
  })

  // 批量操作
  const contractRef = ref()
  const importFileRef = ref()
  const batchPrintRef = ref()
  const handleBatch = (name) => {
    const selection = tableRef.value.$table.getCheckboxRecords()
    let nameArr = ['create','delivery','bill','bill_detail']
    if (!nameArr.includes(name)  &&!selection.length) {
      ElMessage.warning('请先选择行')
      return
    }
    const b_ids = selection.map(d => d.b_id)
    const showLoading = () => loadings[name] = true
    const closeLoading = () => loadings[name] = false
    const handleOpenContract = (type) => {
      const form = tableRef.value.getQueryForm()
      const { yes } = yesno(selection, d => d.billing_status !== 4, false);
      if (!yes?.length && !Object.keys(form).length) {
        return ElMessage.warning('没有可操作的数据！');
      }
      const b_ids = yes?.map(d => d.b_id);
      contractRef?.value.open({ b_ids, ...form }, type);
    };
    const handle = {
      print: async () => {
        batchPrintRef?.value.open(b_ids)
      },
      create: () => handleOpenContract(1),
      delivery: () => handleOpenContract(2),
      bill: () => handleOpenContract(3),
      bill_detail: () => handleOpenContract(4),
      cancel: () => {
        ElMessageBox.confirm('是否确认作废？', '取消', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        })
          .then(() => {
            showLoading()
            api.cancel({ b_ids }).then(res => {
              resMessage({
                res,
                success: () => {
                  ElMessage.success('操作成功')
                  query()
                }
              })
            }).finally(closeLoading)
          })
          .catch(() => {
            ElMessage({ type: 'info', message: '取消操作', })
          })
      },
    }
    handle[name]()
  }

  // 单行操作
  const enterRef = ref()
  const handleRow = (name, row, rowIndex) => {
    const { b_id } = row
    const showLoading = () => {
      loadings[name + rowIndex] = true
    }
    const closeLoading = () => {
      loadings[name + rowIndex] = false
    }
    const handle = {
      enter: () => {
        enterRef?.value.open(b_id)
      },
      detail: () => {
        enterRef?.value.open(b_id, row)
      },
      cancel: () => {
        ElMessageBox.confirm('是否确认作废？', '取消', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        })
          .then(() => {
            showLoading()
            api.cancel({ b_ids: [b_id] }).then(res => {
              resMessage({
                res,
                success: () => {
                  ElMessage.success('操作成功')
                  query()
                }
              })
            }).finally(closeLoading)
          })
          .catch(() => {
            ElMessage({ type: 'info', message: '取消操作', })
          })
      },
      log: () => {
        logRef?.value.open({ log_type: baseName, b_id })
      },
    }
    handle[name]()
  }
  const handlePath = (val) =>{
    sessionStorage.setItem(
      "_table_form",
      JSON.stringify({
        tableForm: { input: { type: 'contract_no', value: val } },
      })
    );
    router.push('/finance/verification/file');
  }
  // 列表配置
  const tableOptions = reactive({
    showHeaderOverflow: false,
    rowConfig: {height: 90},
    formConfig: {
      data: {
        input: { type: 'purchase_no', value: '' },
        skuInfo: { type: 'sku', value: '' },
        dateRange: { type: 'create_time', value: [], range: true },
      }
    },
    columns: [
      { type: 'checkbox', width: 40, fixed: 'left' },
      { title: '开票清单号', field: 'billing_no', minWidth: 160 },
      { title: '文件信息', field: 'billing_no', minWidth: 300,slots:{
          default: ({row})=>{
            return <div>
              <VText title="开票合同" value={row.contract_no} copy type="link">
                <el-link type="primary" onClick={() => handlePath(row.contract_no)}>{row.contract_no}</el-link>
              </VText>
              <VText title="送货清单" value={row.deliver_contract_no} copy type="link">
                <el-link type="primary" onClick={() => handlePath(row.deliver_contract_no)}>{row.deliver_contract_no}</el-link>
              </VText>
              <VText title="开票清单" value={row.list_contract_no} copy type="link">
                <el-link type="primary" onClick={() => handlePath(row.list_contract_no)}>{row.list_contract_no}</el-link>
              </VText>
              <VText title="开票明细" value={row.detail_contract_no} copy type="link">
                <el-link type="primary" onClick={() => handlePath(row.detail_contract_no)}>{row.detail_contract_no}</el-link>
              </VText>
            </div>
          }
        } },
      { title: '公司主体', field: 'company_id_name', minWidth: 140, line: 2 },
      { title: '供应商', field: 'supplier_name', minWidth: 140, line: 2 },
      { title: '采购人员', field: 'purchase_user_name', minWidth: 140, line: 2 },
      { title: '发票类型', field: 'invoice_type_name', minWidth: 100 },
      { title: '入库月份', field: 'inbound_month', minWidth: 100, slots: {
          default: ({ row }) => (
            <div>
              <VText value={row?.inbound_month?.join(",") || "-"}></VText>
            </div>
          ),
        }, },
      { title: '开票品名', field: 'invoice_name', minWidth: 100 },
      { title: '开票单位', field: 'invoice_unit', minWidth: 100 },
      { title: '应开票数量', field: 'billing_num', minWidth: 100 },
      { title: '已开票数量', field: 'invoice_num', minWidth: 100 },
      { title: '待开票数量', field: 'leave_num', minWidth: 100 },
      { title: '文件是否上传', field: 'upload_file_name', minWidth: 100 },
      { title: '实际含税单价', field: 'billing_unit_price_tax', minWidth: 140 },
      { title: '实际含税金额', field: 'actually_inbound_price_tax', minWidth: 140 },
      { title: '开票不含税金额', field: 'total_price', minWidth: 120 },
      { title: '开票税额', field: 'tax_price', minWidth: 100 },
      { title: '供应商含税金额', field: 'supplier_total_price_tax', minWidth: 100 },
      // { title: '流程状态', field: 'billing_status_name', minWidth: 100 },
      {
        minWidth: 80, slots: {
          header: () => <div>录入状态<br />推送状态</div>,
          default: ({ row }) => <div>
            <VText value={row.billing_status_name} />
            <VText value={row.invoice_status_name} />
          </div>
        }
      },
      {
        minWidth: 160, slots: {
          header: () => <div>生成开票人员<br />生成开票时</div>,
          default: ({ row }) => <div>
            <VText value={row.create_user} />
            <VText value={row.create_time} />
          </div>
        }
      },
      {
        title: '操作', width: 180, fixed: 'right', slots: {
          default: ({ row, rowIndex }) => {
            const { billing_status } = row
            // billing_status 流程状态 1待录入 2部分录入 3已录入 4已作废
            return [<div class='nm flex flex-wrap gap-1'>
              {[1,2,3].includes(billing_status) ? <VButton auth="/purchase/finance/verification/billing/invoice" link type="primary" onClick={() => handleRow('enter', row)}>录入发票信息</VButton>: ''}
              {[1].includes(billing_status) ? <VButton auth="/purchase/finance/verification/billing/cancel" link type="primary" onClick={() => handleRow('cancel', row)}>作废</VButton> : ''}
              <VButton link type="primary" onClick={() => handleRow('detail', row)}>详情</VButton>
              <VButton auth="/purchase/finance/verification/billing/log" link type="primary" onClick={() => handleRow('log', row)}>日志</VButton>
            </div>]
          }
        }
      },
    ],
    proxyConfig: {
      autoLoad: false,
      ajax: {
        query: ({ page, form }) => api.query({ ...form, ...page })
      }
    }
  })
</script>
  